package com.example.demo.controller;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Description: 简化流程查询控制器
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author 作者名称 用户名
 * @date 2025/1/15 17:29
 */
@RestController
@RequestMapping("/api/simple")
public class SimpleProcessController {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询流程实例的当前任务和责任人
     *
     * @param processInstanceId 流程实例ID
     * @return 查询结果
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/task/{processInstanceId}")
    public Map<String, Object> getCurrentTaskInfo(@PathVariable("processInstanceId") String processInstanceId) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            // 查询流程实例
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            
            if (processInstance != null) {
                // 流程实例基本信息
                result.put("processInstanceId", processInstanceId);
                result.put("processDefinitionId", processInstance.getProcessDefinitionId());
                result.put("businessKey", processInstance.getBusinessKey());
                result.put("startTime", processInstance.getStartTime());
                result.put("startUserId", processInstance.getStartUserId());
                result.put("isEnded", processInstance.isEnded());
                result.put("isSuspended", processInstance.isSuspended());
                
                // 查询当前任务
                List<Task> activeTasks = taskService.createTaskQuery()
                        .processInstanceId(processInstanceId)
                        .active()
                        .list();
                
                if (activeTasks.isEmpty()) {
                    result.put("currentTask", "无当前任务");
                    result.put("assignee", "无");
                    result.put("message", "流程实例存在但无活跃任务");
                } else {
                    result.put("currentTaskCount", activeTasks.size());
                    
                    List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
                    for (Task task : activeTasks) {
                        Map<String, Object> taskInfo = new HashMap<String, Object>();
                        taskInfo.put("taskId", task.getId());
                        taskInfo.put("taskName", task.getName());
                        taskInfo.put("assignee", task.getAssignee());
                        taskInfo.put("createTime", task.getCreateTime());
                        taskInfo.put("dueDate", task.getDueDate());
                        taskInfo.put("priority", task.getPriority());
                        taskInfo.put("description", task.getDescription());
                        taskInfo.put("owner", task.getOwner());
                        
                        taskList.add(taskInfo);
                    }
                    
                    result.put("currentTasks", taskList);
                    
                    // 显示第一个任务的主要信息
                    Task firstTask = activeTasks.get(0);
                    result.put("currentTask", firstTask.getName());
                    result.put("assignee", firstTask.getAssignee());
                }
                
            } else {
                // 查询历史流程实例
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult();
                
                if (historicProcessInstance != null) {
                    result.put("processInstanceId", processInstanceId);
                    result.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());
                    result.put("startTime", historicProcessInstance.getStartTime());
                    result.put("endTime", historicProcessInstance.getEndTime());
                    result.put("duration", historicProcessInstance.getDurationInMillis());
                    result.put("startUserId", historicProcessInstance.getStartUserId());
                    result.put("deleteReason", historicProcessInstance.getDeleteReason());
                    result.put("status", "COMPLETED");
                    result.put("currentTask", "流程已完成");
                    result.put("assignee", "无");
                    result.put("message", "流程已完成");
                } else {
                    result.put("error", "流程实例不存在");
                    result.put("processInstanceId", processInstanceId);
                }
            }
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
            result.put("processInstanceId", processInstanceId);
        }
        
        return result;
    }

    /**
     * 查询所有活跃的流程实例
     *
     * @return 所有活跃流程实例
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/processes")
    public Map<String, Object> getAllActiveProcesses() {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            List<ProcessInstance> processes = runtimeService.createProcessInstanceQuery()
                    .active()
                    .list();
            
            result.put("count", processes.size());
            
            List<Map<String, Object>> processList = new ArrayList<Map<String, Object>>();
            for (ProcessInstance process : processes) {
                Map<String, Object> processInfo = new HashMap<String, Object>();
                processInfo.put("processInstanceId", process.getId());
                processInfo.put("processDefinitionId", process.getProcessDefinitionId());
                processInfo.put("businessKey", process.getBusinessKey());
                processInfo.put("startTime", process.getStartTime());
                processInfo.put("startUserId", process.getStartUserId());
                processInfo.put("isEnded", process.isEnded());
                processInfo.put("isSuspended", process.isSuspended());
                
                processList.add(processInfo);
            }
            
            result.put("processes", processList);
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 查询所有活跃任务
     *
     * @return 所有活跃任务
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/tasks")
    public Map<String, Object> getAllActiveTasks() {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            List<Task> tasks = taskService.createTaskQuery()
                    .active()
                    .list();
            
            result.put("count", tasks.size());
            
            List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
            for (Task task : tasks) {
                Map<String, Object> taskInfo = new HashMap<String, Object>();
                taskInfo.put("taskId", task.getId());
                taskInfo.put("taskName", task.getName());
                taskInfo.put("processInstanceId", task.getProcessInstanceId());
                taskInfo.put("assignee", task.getAssignee());
                taskInfo.put("createTime", task.getCreateTime());
                taskInfo.put("dueDate", task.getDueDate());
                taskInfo.put("priority", task.getPriority());
                taskInfo.put("description", task.getDescription());
                taskInfo.put("owner", task.getOwner());
                
                taskList.add(taskInfo);
            }
            
            result.put("tasks", taskList);
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 查询指定用户的任务
     *
     * @param assignee 责任人
     * @return 用户任务列表
     * @author 作者姓名
     * @date 2025/1/15 17:29
     */
    @GetMapping("/user-tasks/{assignee}")
    public Map<String, Object> getUserTasks(@PathVariable("assignee") String assignee) {
        Map<String, Object> result = new HashMap<String, Object>();
        
        try {
            List<Task> tasks = taskService.createTaskQuery()
                    .taskAssignee(assignee)
                    .active()
                    .list();
            
            result.put("assignee", assignee);
            result.put("count", tasks.size());
            
            List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
            for (Task task : tasks) {
                Map<String, Object> taskInfo = new HashMap<String, Object>();
                taskInfo.put("taskId", task.getId());
                taskInfo.put("taskName", task.getName());
                taskInfo.put("processInstanceId", task.getProcessInstanceId());
                taskInfo.put("assignee", task.getAssignee());
                taskInfo.put("createTime", task.getCreateTime());
                taskInfo.put("dueDate", task.getDueDate());
                taskInfo.put("priority", task.getPriority());
                taskInfo.put("description", task.getDescription());
                
                taskList.add(taskInfo);
            }
            
            result.put("tasks", taskList);
            
        } catch (Exception e) {
            result.put("error", "查询失败: " + e.getMessage());
        }
        
        return result;
    }
}
